<template>
  <el-form ref="formRef" :model="formData" label-width="135px" label-position="left">
    <at-form-group v-model="formData" :json="formJson"> </at-form-group>
    <slot></slot>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'
import http from '@/utils/http'
import { ElMessageBox, ElMessage } from 'element-plus'

const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  data: Object,
  from: String,
})

const formRef = ref()
const formData = ref({})

watch(
  () => props.data,
  val => {
    const config = {
      temperature: 0,
    }

    if (props.from == 'llm_init') {
      config.enable = true
    }

    formData.value = {
      ...config,
      ...props.data,
    }
  },
  {
    immediate: true,
  },
)

const llms = [
  { label: 'ollama', value: 'ollama', url: 'http://127.0.0.1:11434/api/v1' },
  {
    label: 'OpenRouter',
    value: 'openrouter',
    url: 'https://openrouter.ai/api/v1',
    model: 'qwen/qwen3-30b-a3b:free',
  },
  { label: 'qwen3', value: 'vllm_qwen3' },
  { label: 'deepseek', value: 'deepseek', url: 'https://api.deepseek.com/v1' },
]

const formJson = computed(() => {
  return [
    {
      label: '模型类型',
      name: 'type',
      type: 'select',
      options: llms,
      required: true,
      inputAttr: {
        // filterable: true,
        onChange(val) {
          const llm = llms.find(item => item.value == val)
          formData.value.api = llm.url
          formData.value.model = llm.model
        },
      },
    },
    { label: '模型名称', name: 'model', required: true },
    { label: 'API地址', name: 'api', required: true },
    { label: 'API密钥', name: 'key', type: 'textarea' },
    {
      label: '模型温度',
      name: 'temperature',
      type: 'input-number',
      // tips: '控制生成结果的多样性和随机性。数值越小，越严谨;数值越大，越发散。',
      inputAttr: {
        precision: '1',
        step: '0.1',
        max: '2',
      },
    },
    { label: '深度思考', name: 'think', type: 'switch' },

    ...(() => {
      const json = []

      if (props.from != 'llm_init') {
        json.push({
          label: '模型启用',
          name: 'enable',
          type: 'switch',
        })
      }

      return json
    })(),
  ]
})

const submit = cb => {
  formRef.value.validate().then(val => {
    const body = { ...formData.value }

    if (body.id) {
      http.put('/hids/llm/config', body).then(() => {
        ElMessage.success('修改成功')
        cb()
      })
    } else {
      http.post('/hids/llm/config', body).then(() => {
        ElMessage.success('添加成功')
        cb()
      })
    }
  })
}

defineExpose({
  submit,
  formData,
})
</script>

<style lang="scss" scoped></style>
